package com.perceptivesoftware.licensing.client.common.util;

import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.google.gwt.user.client.Timer;

/**
 * This class controls the automatic timeout feature of Perceptive Licensing. This is used
 * in both the admin and user modes. This uses a simple javascript timer and
 * will present a logoff warning to the user at sessionTimeoutMins -
 * warnTimeMins. The user can reset their extension by The timer is also reset
 * on any RPC call. Its important that this timer is < the HttpSession timer.
 *
 * Copyright 2012 Perceptive Software Confidential and Proprietary
 *
 */
public class LogoffTimer extends Timer
{
	boolean currentlyWarning = false;
	private MessageBox m;
	private final LogoffHandler logoffHandler;

	private Long sessionTimeoutMins = ClientConstants.DEFAULT_LOGOFF_INTERVAL_MINUTES;
	private final Long warnTimeMins = ClientConstants.DEFAULT_LOGOFF_WARN_TIME_MINUTES;

	public LogoffTimer(final LogoffHandler logoffHandler)
	{
		this.logoffHandler = logoffHandler;
		reset();
	}

	public void configureTimeout(final Long _sessionTimeoutMins)
	{
		// if (_sessionTimeoutMins != null){
		sessionTimeoutMins = _sessionTimeoutMins;
		reset();
		// }
	}

	public void reset()
	{
		if (m != null)
		{
			m.close();
		}
		cancel();
		currentlyWarning = false;
		schedule();
	}

	public void schedule()
	{
		final int ms = (sessionTimeoutMins.intValue() - warnTimeMins.intValue()) * ClientConstants.MS_PER_MINUTE;
		schedule(ms);
	}

	@Override
	public void run()
	{
		if (currentlyWarning)
		{
			logoffHandler.logoff(true);
		}
		else
		{
			currentlyWarning = true;
			m = MessageBox.alert("Perceptive Licensing Logout", "You will be automatically logged out in " + warnTimeMins + " minutes. Click OK to stay logged in.", new Listener<MessageBoxEvent>() {
				@Override
				public void handleEvent(final MessageBoxEvent be)
				{
					reset();
				}
			});
			final int ms = warnTimeMins.intValue() * ClientConstants.MS_PER_MINUTE;
			// Utils.debugMessage("Logoff Warning given, will log off in " +
			// ClientConstants.LOGOFF_WARN_TIME_MINUTES + " minutes.");
			schedule(ms);
		}
	}

	public interface LogoffHandler
	{
		abstract void logoff(boolean timeout);
	}

}